package tgc.edu.demo.jkxt.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tgc.edu.demo.jkxt.custom.BaseService;
import tgc.edu.demo.jkxt.entity.SysRole;
import tgc.edu.demo.jkxt.entity.Teacher;
import tgc.edu.demo.jkxt.form.TeacherForm;
import tgc.edu.demo.jkxt.repository.TeacherRepository;

@Service
public class TeacherService extends BaseService<Teacher, Integer> {
	@Autowired
	private SysRoleService sysRoleservice;
	@Autowired
	private TeacherRepository teacherRepository;
	
	@Transactional
	public synchronized Boolean save(TeacherForm form) {
		try {
			BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
			Integer id = form.getId();
			Teacher model=new Teacher();
			if(id!=null) {
				model=findById(id);
			}else {
				model.setPassword(encoder.encode("1234"));
				List<SysRole> role=new ArrayList<SysRole>();
				role.add(sysRoleservice.findById(2));
				model.setRoles(role);
			
			}
			
			BeanUtils.copyProperties(form, model,"id");
			save(model);
			return true;
		} catch (Exception e) {
			return false;
		}
		
	}
}
